package com.examplemartin.jpademo.service.admin;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.dao.admin.DatabaseDao;
import com.examplemartin.jpademo.pojo.po.DatabasePO;
import com.examplemartin.jpademo.util.DateUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DatabaseService {

  @Resource
  private DatabaseDao databaseDao;

  @Resource
  private OperatorLogService operatorLogService;


  public List<DatabasePO> findAllPage(Pageable page) {
    if (page == null) {
      page = PageRequest.of(0, 10);
    }

    Page<DatabasePO> all = databaseDao.findAll(page);
    List<DatabasePO> content = all.getContent();
    return content;
  }

  public Long countAll(){
    return databaseDao.count();
  }

  /**
   * 备份数据库
   */
  public AjaxResult backup(String dburl,String username,String password,String target)
       {

    // jdbc:mysql://localhost:3306/jpademo?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai

    String str = dburl;

    // 处理 dburl字符串  获取 dbname , port , dbsite
    // jdbc:mysql://localhost:3306/jpademo
    String temp01 = str.substring(0,str.indexOf("?"));


    // jpademo
    String dbname = temp01.substring(temp01.lastIndexOf("/")+1,temp01.length());

    // jdbc:mysql://localhost:3306
    String temp02 = temp01.substring(0,temp01.lastIndexOf("/"));
    log.info("temp02 = "+temp02);

    // port
    String port = temp02.substring(temp02.lastIndexOf(":")+1,temp02.length());

    // dbsit
    String dbsite = temp02.substring(temp02.lastIndexOf("/")+1,temp02.lastIndexOf(":"));
// 结束处理 dburl字符串  获取 dbname , port , dbsite


    String cmd= "mysqldump -h"+dbsite+" -P"+port+" -u"+username+" -p"+password + " " +dbname+" -r "+target;


    // 保存备份记录
         // 保存
         DatabasePO databasePO = new DatabasePO();
         databasePO.setFilename(target);
         databasePO.setCreateTime(new Date());


         databasePO=databaseDao.save(databasePO);

         // 开始备份

         try {
           Process exec = Runtime.getRuntime().exec(cmd);
           //取得命令结果的输出流
           InputStream fis=exec.getInputStream();
           //用一个读输出流类去读
           InputStreamReader isr=new InputStreamReader(fis);
           //用缓冲器读行
           BufferedReader br=new BufferedReader(isr);
           String line=null;
           //直到读完为止
           while((line=br.readLine())!=null)
           {
             System.out.println(line);
           }

           /*if(exec.waitFor()==0){



             return AjaxResult.success(200,"备份文件:"+target+" 成功恢复",null);
           }*/
           exec.destroy();
         } catch (IOException  e) {
           e.printStackTrace();
           databaseDao.delete(databasePO);
           return AjaxResult.success(500,e.getMessage(),null);

         }

         File bak = new File(target);
         if(!bak.exists()||bak.length()<=0){
           databaseDao.delete(databasePO);
           return AjaxResult.success(500,"未能正常完成备份 请联系程序员",null);
         }

         // 保存

         databasePO.setSize(bak.length());

         databaseDao.save(databasePO);




         return AjaxResult.success(200,"成功备份-"+target,null);
  }


  /**
   * 删除备份
   */
  public AjaxResult deleteById(Long id) {
    DatabasePO byId = findById(id);
    String filename = byId.getFilename();
    File file = new File(filename);
    boolean b = file.renameTo(new File(filename + ".del"));

    if(!b){
      return AjaxResult.fail(500,"备份文件删除失败-"+filename);
    }


    File test = new File(filename);

    if(test.exists()){
            return AjaxResult.fail(500,"未能删除 备份文件:"+filename+" 删除失败");
    }


    databaseDao.deleteById(id);
    return AjaxResult.success(200,"备份文件:"+filename+" 成功删除",null);

  }

  /**
   * 找找备份
   */
  public DatabasePO findById(Long id) {
    Optional<DatabasePO> byId = databaseDao.findById(id);
    return byId.get();
  }

  /**
   * 添加注释
   */
  public AjaxResult saveComment(DatabasePO databasePO) {
    DatabasePO byId = databaseDao.findById(databasePO.getId()).get();

    byId.setUpdateTime(new Date());
    byId.setComment(databasePO.getComment());

    DatabasePO save = databaseDao.save(byId);
    if(save==null){
      return AjaxResult.fail(500,byId.getFilename()+"注释添加失败");
    }else{
      return AjaxResult.success(200,byId.getFilename()+"成功修改注释",null);
    }

  }

  /**
   * 备份恢复
   */
  public AjaxResult restoreDb(DatabasePO databasePO,String dburl,String username,String password)
      throws IOException {

    DatabasePO byId = databaseDao.findById(databasePO.getId()).get();

    // jdbc:mysql://localhost:3306/jpademo?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai

    String str = dburl;

    // 处理 dburl字符串  获取 dbname , port , dbsite
    // jdbc:mysql://localhost:3306/jpademo
    String temp01 = str.substring(0,str.indexOf("?"));


    // jpademo
    String dbname = temp01.substring(temp01.lastIndexOf("/")+1,temp01.length());

    // jdbc:mysql://localhost:3306
    String temp02 = temp01.substring(0,temp01.lastIndexOf("/"));
    log.info("temp02 = "+temp02);

    // port
    String port = temp02.substring(temp02.lastIndexOf(":")+1,temp02.length());

    // dbsit
    String dbsite = temp02.substring(temp02.lastIndexOf("/")+1,temp02.lastIndexOf(":"));
// 结束处理 dburl字符串  获取 dbname , port , dbsite

    // 备份临时文件
    File file = new File(byId.getFilename());
    String tmpfilename =byId.getFilename()+".tmp-"+ DateUtil.getBackupFileName();
    File tmp = new File(tmpfilename);
    Files.copy(file.toPath(),tmp.toPath());

    String cmd= "cmd /c mysql -h"+dbsite+" -P"+port+" -u"+username+" -p"+password + " " +dbname+" <"+byId.getFilename();


    // 开始恢复备份

    try {
      Process exec = Runtime.getRuntime().exec(cmd);
      //取得命令结果的输出流
      InputStream fis=exec.getInputStream();
      //用一个读输出流类去读
      InputStreamReader isr=new InputStreamReader(fis);
      //用缓冲器读行
      BufferedReader br=new BufferedReader(isr);
      String line=null;
      //直到读完为止
      while((line=br.readLine())!=null)
      {
        System.out.println(line);
      }

      if(exec.waitFor()==0){
        byId.setUpdateTime(new Date());
        databaseDao.save(byId);
        return AjaxResult.success(200,"备份文件:"+byId.getFilename()+" 成功恢复",null);
      }
      exec.destroy();
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
      return AjaxResult.success(500,e.getMessage(),null);

    }

    return AjaxResult.success(200,"备份文件:"+byId.getFilename()+" 成功恢复",null);
  }
}
